const { body, query } = require("express-validator");
const { id, pageno, pagesize } = require("../common");

const username = (optional = false) => {
    if (optional) {
        return body("username")
            .optional()
            .trim()
            .notEmpty()
            .withMessage("用户名不能为空")
            .bail()
            .custom((value) => {
                if (!/^[a-zA-Z0-9_]{4,16}$/.test(value)) {
                    throw new Error("用户名格式错误");
                }
                return true;
            });
    } else {
        return body("username")
            .trim()
            .notEmpty()
            .withMessage("用户名不能为空")
            .bail()
            .custom((value) => {
                if (!/^[a-zA-Z0-9_]{4,16}$/.test(value)) {
                    throw new Error("用户名格式错误");
                }
                return true;
            });
    }
};

const password = (optional = false) => {
    if (optional) {
        return body("password")
            .optional()
            .trim()
            .notEmpty()
            .withMessage("密码不能为空")
            .bail()
            .isLength({ min: 6 })
            .custom((value) => {
                if (!/[A-Z]/.test(value))
                    throw new Error("密码必须包含至少一个大写字母");
                if (!/[0-9]/.test(value))
                    throw new Error("密码必须包含至少一个数字");
                return true;
            });
    } else {
        return body("password")
            .trim()
            .notEmpty()
            .withMessage("密码不能为空")
            .bail()
            .isLength({ min: 6 })
            .custom((value) => {
                if (!/[A-Z]/.test(value))
                    throw new Error("密码必须包含至少一个大写字母");
                if (!/[0-9]/.test(value))
                    throw new Error("密码必须包含至少一个数字");
                return true;
            });
    }
};

const avatar = (optional = false) => {
    if (optional) {
        return body("avatar")
            .optional()
            .trim()
            .notEmpty()
            .withMessage("头像不能为空");
    } else {
        return body("avatar").trim().notEmpty().withMessage("头像不能为空");
    }
};

const isActive = body("isActive")
    .optional()
    .trim()
    .notEmpty()
    .withMessage("是否启用不能为空")
    .bail()
    .isBoolean()
    .withMessage("是否启用只能是布尔值");

module.exports = {
    list: [pageno, pagesize],
    add: [username(), password(), avatar()],
    login: [username(), password()],
    update: [id, password(true), avatar(true), isActive],
    delete: [id],
    detail: [id],
    download: [id],
    rating: [id]
};
